package com.konka.spring.framework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author konka
 * @date 2023/2/10
 * @description:
 */
public class View {

    private File viewFile;

    public View(File viewFile) {
        this.viewFile = viewFile;
    }

    /**
     * 处理模板文件中需要替换的字符串，拼装好后写到浏览器
     * @param model
     * @param req
     * @param resp
     * @throws Exception
     */
    public void render(Map<String,?>model, HttpServletRequest req, HttpServletResponse resp) throws Exception{
        StringBuffer sb = new StringBuffer();
        //r -> reading only
        RandomAccessFile randomAccessFile = new RandomAccessFile(this.viewFile,"r");
        String line = null;
        while ((null != (line = randomAccessFile.readLine()))){
            line = new String(line.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);

            Pattern pattern = Pattern.compile("￥\\{[^\\}]+\\}", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()){
                String paramName = matcher.group();

                paramName = paramName.replaceAll("￥\\{|\\}", "");
                Object paramValue = model.get(paramName);
                if (paramValue == null){ continue; }
                line = matcher.replaceFirst(makeStringForRegExp(paramValue.toString()));
                matcher = pattern.matcher(line);
            }
            sb.append(line);
        }
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(sb.toString());

    }

    /**
     * 处理特殊字符
     * @param str
     * @return
     */
    public static String makeStringForRegExp(String str){
        return str.replace("\\","\\\\").replace("*","\\*")
                .replace("+","\\+").replace("|","\\|")
                .replace("{","\\{").replace("}","\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }
}
